package com.ai.zuochengyun.phase01.class03;

/**
 * 用数组实现队列
 */
public class Code01_RingArray {

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue(4);
        for (int i = 0; i < 100; i++) {
            // 获取1~100之间的数
            int value = (int)(Math.random() * 100) + 1;
            try {
                if (value % 2 == 0) {
                    System.out.println("插入的元素："+value);
                    myQueue.push(value);
                } else {
                    System.out.println("取出的元素："+myQueue.pop());
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static class MyQueue {
        private final int[] arr;
        private int pushIndex;
        private int pollIndex;
        private int size;
        private final int capacity;

        public MyQueue(int capacity) {
            this.arr = new int[capacity];
            this.pushIndex = 0;
            this.pollIndex = 0;
            this.size = 0;
            this.capacity = capacity;
        }

        public void push(int value) throws Exception {
            if (size >= capacity) {
                throw new Exception("队列已满，不能插入数据");
            }

            size++;
            arr[pushIndex] = value;
            pushIndex = nextIndex(pushIndex);
        }

        public int pop() throws Exception {
            if (size <= 0) {
                throw new Exception("队列已空，不能获取数据");
            }

            size--;
            int ans = arr[pollIndex];
            pollIndex = nextIndex(pollIndex);
            return ans;
        }

        public int nextIndex(int index) {
            // 如果下标来到了n-1位置，则重新从0位置开始，循环，周而复始
            if (index == capacity - 1) {
                return 0;
            }
            return index+1;
        }
    }

}
